package demo.controller;

import demo.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

class LoginInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("拦截器执行了@@@@@");
        //获取登录 的信息
        User user = (User) request.getSession().getAttribute("DL");
        //判断登录信息 是否正常
        if(user!=null){
            if(user.getRole().equals("adm")){
                String s=request.getRequestURI();
                if (s.startsWith("/clz")||s.startsWith("/course")||s.startsWith("/teaadm")||s.startsWith("/stuadm")||s.startsWith("/task")||s.startsWith("/home"))
                    return true;
                response.sendRedirect("/home/go2login");
                return false;
            }else if(user.getRole().equals("stu")){
                String s=request.getRequestURI();
                if (s.startsWith("/stu")||s.startsWith("/home"))  return true;
                response.sendRedirect("/home/go2login");
                return false;
            }else if(user.getRole().equals("tea")){
                String s=request.getRequestURI();
                if (s.startsWith("/tea")||s.startsWith("/home"))  return true;
                response.sendRedirect("/home/go2login");
                return false;
            }
//            System.out.println("用户已经登录正常执行");
            return true;
        }else{
//            System.out.println("用户没有登录，就转发到登录界面");
            //转发登录界面
            response.sendRedirect("/home/go2login");
            return false;
        }


    }

    /**
     * 该方法触发在请求已被控制器处理完毕，返回视图之前，不是很常用，通常是用来完善处理器结果的

     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    /**
     * 这个方法在控制器视图解析全部完成之后，最后执行，通常用来做一些扫尾工作，基本不用
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
